package com.stefanini.pe.bbva.mbl.in.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.stefanini.pe.bbva.mbl.in.utils.Constantes;

public class SessionFilter implements Filter {
	private static Logger logger = Logger.getLogger(SessionFilter.class);

	public void init(FilterConfig config) throws ServletException {
	}

	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
		throws ServletException, IOException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
		HttpSession session = request.getSession();
		Object strNombreUsuarioSesion = (Object) session.getAttribute(Constantes.USUARIO_SESSION);
		String requestURI = request.getRequestURI();
		String urlAllow1 = request.getContextPath() + "/index.jsp";
		String urlAllow2 = request.getContextPath() + "/login.jsf";
		String urlAllow3 = request.getContextPath() + "/sinAcceso.jsp";
		String urlAllow4 = request.getContextPath() + "/opcionnopermitida.jsf";
		String urlAllow5 = request.getContextPath() + "/ldapacceso.jsf";
		String urlAllow6 = request.getContextPath() + "/gnrerror.htm";
		String urlAllow7 = request.getContextPath() + "/pages/consultas/chartcreatorrequest.jsf";
		String urlAllow8 = request.getContextPath() + "/pages/mantenimiento/validatorResource.jsf";
		String urlAllow9 = request.getContextPath() + "/faces/principal.jsp";
		
		if (strNombreUsuarioSesion != null 
				|| requestURI.equals(urlAllow1)
				|| requestURI.equals(urlAllow2)
				|| requestURI.equals(urlAllow3)
				|| requestURI.equals(urlAllow4)
				|| requestURI.equals(urlAllow5)
				|| requestURI.equals(urlAllow6)
				|| requestURI.equals(urlAllow7)
				|| requestURI.equals(urlAllow8)
				|| requestURI.equals(urlAllow9)) {
				try{
					chain.doFilter(req, resp);
				}
				catch(Exception e){
					e.printStackTrace();
				}
		}else {
			logger.info("[SessionFilter :: doFilter] No hay sesion se redirecciona a login");
			response.sendRedirect(urlAllow2);
		}		
	}

	public void destroy() {
	}
}
